package org.cjlm.ui.template;

import org.cjlm.ui.pub.QueryItem;
import org.cjlm.vo.SuperVO;
import org.cjlm.vo.template.TemplateAVO;
import org.cjlm.vo.template.TemplateBVO;
import org.cjlm.vo.template.TemplateMVO;

import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;

public class QueryDialog extends JDialog {
    private TemplateMVO mvo;
    private final JButton btnConfirm = new JButton("确认");
    private final JButton btnCancel = new JButton("取消");
    private boolean confirmed = false;
    private final List<QueryItem> conditionPanels = new ArrayList<>();

    public QueryDialog(TemplateMVO mvo) {
        super((Frame) null, true);
        this.mvo = mvo;
        initUI();
    }

    private void initUI() {
        setSize(500, 300);
        setLayout(new BorderLayout());
        setLocationRelativeTo(null);

        String title = null;
        // 创建条件面板
        JPanel conditionsPanel = new JPanel(new GridLayout(4, 1, 5, 10));
        if(this.mvo != null) {
            List<SuperVO> avolist = this.mvo.getChildren();
            for (SuperVO avol : avolist) {
                TemplateAVO avo = (TemplateAVO) avol;
                if (avo.getType() == 2) {//查询模板
                    title = avo.getName();
                    List<SuperVO> bvolist = avo.getChildren(TemplateBVO.class.getName());
                    for(SuperVO bvol : bvolist){
                        TemplateBVO bvo = (TemplateBVO) bvol;
                        conditionPanels.add(new QueryItem(bvo.getCode(),bvo.getName()));
                    }
                    break;
                }
            }
        }

        setTitle(title);
        for (QueryItem panel : conditionPanels) {
            conditionsPanel.add(panel);
        }

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        btnConfirm.addActionListener(e  -> confirm());
        btnCancel.addActionListener(e  -> cancel());
        buttonPanel.add(btnConfirm);
        buttonPanel.add(btnCancel);

        add(new JLabel("请输入查询条件：", JLabel.LEFT), BorderLayout.NORTH);
        add(new JScrollPane(conditionsPanel), BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);
    }

    private void confirm() {
        confirmed = true;
        dispose();
    }

    private void cancel() {
        confirmed = false;
        dispose();
    }

    public boolean isConfirmed() {
        return confirmed;
    }

    // 构建WHERE子句
    public String buildWhereClause() {
        List<String> conditions = new ArrayList<>();
        for (QueryItem item : conditionPanels) {
            String condition = item.getCondition();
            if (!condition.isEmpty())  {
                conditions.add(condition);
            }
        }
        return String.join("  AND ", conditions);
    }
}